package com.chinawayltd.ews.sample.config;

import com.chinawayltd.ews.openapi.OpenApiClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

import static com.chinawayltd.ews.openapi.enums.EnvPropertyEnum.ACCESS_ID;
import static com.chinawayltd.ews.openapi.enums.EnvPropertyEnum.BASE_URL;
import static com.chinawayltd.ews.openapi.enums.EnvPropertyEnum.SECRET_KEY;

/**
 * @program: greeProject.timingTaskCenter
 * @description:
 * @author: xiazj
 * @create: 2018-04-24 11:48
 **/
@Configuration
public class InterfaceConfig {

    private static Logger LOGGER = LoggerFactory.getLogger(InterfaceConfig.class);

    @Value("${orgConfig.orgCode}")
    private String orgCode;
    @Value("${g7ews.openapi.customUrl}")
    private String customUrl;
    @Value("${g7ews.openapi.accessId}")
    private String accessId;
    @Value("${g7ews.openapi.secretKey}")
    private String secretKey;

    public static String ORG_CODE;

    @PostConstruct
    private void init(){
        InterfaceConfig.ORG_CODE = this.orgCode;
    }

    @Bean(name = "customOpenApiClient")
    OpenApiClient getOpenApiClient() {

        String warnInfo = "openApiClient创建失败。原因: 没有配置{}或者环境变量{}。如果不需要使用OpenApi,请忽略。";
        if (customUrl == null) {
            LOGGER.warn(warnInfo, BASE_URL.getPropertyKey(), BASE_URL.getSystemEnvKey());
            return null;
        }
        if (accessId == null) {
            LOGGER.warn(warnInfo, ACCESS_ID.getPropertyKey(), ACCESS_ID.getSystemEnvKey());
            return null;
        }
        if (secretKey == null) {
            LOGGER.warn(warnInfo, SECRET_KEY.getPropertyKey(), SECRET_KEY.getSystemEnvKey());
            return null;
        }

        return new OpenApiClient(customUrl, accessId, secretKey);
    }

}
